
layui.use(['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'form', 'element'], function() {
    var laydate = layui.laydate //日期
        , laypage = layui.laypage //分页
        , layer = layui.layer //弹层
        , table = layui.table //表格
        , $ = layui.jquery
        , form = layui.form
        , element = layui.element; //元素操作
    var userall = document.getElementById("row");
    var userallw = (userall.offsetWidth) / 12;
    var userallt = userallw + 20;
    var useralln = userallw + 60;
    console.log(userallw);

    var u_s_a = document.getElementById("usersuma");
    var u_s_h = u_s_a.offsetHeight - 120;

    var datetime = '';

    var table_format_usersum = [[
                    // {checkbox: true, rowspan:2}
                    {field: 'shop_name', align: 'center', title: '公司简称', rowspan:2, width: userallt}
                    ,{field: 'shop_no_sql', align: 'center', title: '未绑定用户店铺', rowspan:2, width: useralln,sort: true}
                    , {align: 'center', title: '导入店铺详情', colspan: 2}
                    , {align: 'center', title: '上线店铺详情', colspan: 2}
                    , {align: 'center', title: '臻E盾用户详情', colspan: 2}
                    , {align: 'center', title: '臻中心用户详情', colspan: 2}
                    , {align: 'center', title: '臻护卫用户详情', colspan: 2}
                    , {align: 'center', title: '臻总管用户详情', colspan: 2}
                    , {fixed: 'right', width: 100, align: 'center', toolbar: '#upbarDemo', rowspan:2, title: '其他'}
                ],[
                    {field: 'shop_dr', align: 'center', width: userallw, sort: true, title: '总量'}
                    , {field: 'shop_dr_a', align: 'center', width: userallw, sort: true, title: '增长量', style:'background-color: #5FB878; color: #fff;'}
                    , {field: 'shop_on', align: 'center', width: userallw, sort: true, title: '总量'}
                    , {field: 'shop_on_a', align: 'center', width: userallw, sort: true, title: '增长量', style:'background-color: #5FB878; color: #fff;'}
                    , {field: 'user_ed', align: 'center', width: userallw, sort: true, title: '总量'}
                    , {field: 'user_ed_a', align: 'center', width: userallw, sort: true, title: '增长量', style:'background-color: #5FB878; color: #fff;'}
                    , {field: 'user_zx', align: 'center', width: userallw, sort: true, title: '总量'}
                    , {field: 'user_zx_a', align: 'center', width: userallw, sort: true, title: '增长量', style:'background-color: #5FB878; color: #fff;'}
                    , {field: 'user_hw', align: 'center', width: userallw, sort: true, title: '总量'}
                    , {field: 'user_hw_a', align: 'center', width: userallw, sort: true, title: '增长量', style:'background-color: #5FB878; color: #fff;'}
                    , {field: 'user_zg', align: 'center', width: userallw, sort: true, title: '总量'}
                    , {field: 'user_zg_a', align: 'center', width: userallw, sort: true, title: '增长量', style:'background-color: #5FB878; color: #fff;'}
            ]];

    Date.prototype.format = function(fmt) { //author: meizz
        var o = {
                "M+" : this.getMonth()+1,                 //月份
                "d+" : this.getDate(),                    //日
                "h+" : this.getHours(),                   //小时
                "m+" : this.getMinutes(),                 //分
                "s+" : this.getSeconds(),                 //秒
                "q+" : Math.floor((this.getMonth()+3)/3),   //季度
                "S"  : this.getMilliseconds()             //毫秒
        };
        if(/(y+)/.test(fmt))
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        for(var k in o)
            if(new RegExp("("+ k +")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));

        return fmt;
    };


    var newdate;
    laydate.render({
        id:'datetimes'
        ,elem: '#datetimes'
        ,range: true
        // ,format: 'yyyy-MM-dd'
        ,max: new Date().format("yyyy-MM-dd")
        ,min: '2017-01-01'
        ,done: function(value, date, endDate){
            // console.log(value); //得到日期生成的值，如：2017-08-18
            // console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
            // console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
            datetime = value;
            newdate = value;
            if (datetime !== ""){
                $.ajax({
                    url: '/user-sum-send/'
                    ,dataType: 'json'
                    ,type: 'POST'
                    ,data: {'date':datetime}
                    ,success: function (uss_data) {
                        console.log(uss_data);
                        usersum.reload({
                            data:uss_data["usersum_data_send"]
                        })
                    }
                })
            }
        }
    });


    $('.layui-table').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        var sortid = 'sort(' + tableid + ')';
        var begintime = new Date(new Date().getTime()-6*24*60*60*1000);
        var begin = new Date(begintime).format("yyyy-MM-dd");
        var end = new Date().format("yyyy-MM-dd");
        datetime = begin + " " + end;
        newdate=datetime;
        //var tableid = document.getElementById('update').id;
        $.ajax({
            url: '/user-sum-send/'
            ,dataType: 'json'
            ,type: 'POST'
            ,data: {'date':datetime}
            ,success: function (uss_data) {
                createtable(etaleid,tableid,uss_data["usersum_data_send"],table_format_usersum,toolid,sortid, u_s_h);
                usersumtool(toolid, tableid, sortid);
            }
        });
    });

    var usersum;
    var createstattus = 0;
    //执行渲染
    function createtable(etaleid,tableid,datas,table_format,toolid, sortid, heights) {
        usersum = table.render({
            elem: etaleid,
            id: tableid,
            //url: '/demo/table/user/',
            limit:10,
            page: true,
            height:heights,
            // initSort: {field: "shop_dr", type: "asc"},
            // stateSave: true, //是否打开客户端状态记录功能,此功能在ajax刷新纪录的时候不会将个性化设定回复为初始化状态
            // processing: true, //DataTables载入数据时，是否显示‘进度’提示
            // scrollCollapse: true, //是否开启DataTables的高度自适应，当数据条数不够分页数据条数的时候，插件高度是否随数据条数而改变
            // searching: true, //是否允许Datatables开启本地搜索
            data:datas,
            cols:table_format
        });



        // if (tableid === 'update') {
        active = {
            otherdata: function () {
                $.ajax({
                    url: "/other-user-data/",
                    dataType: 'json',
                    type: 'POST',
                    success: function (other_data) {
                        console.log(other_data);
                        layer.open({
                            type: 1,
                            title: false, //不显示标题栏
                            closeBtn: false,
                            area: '300px;',
                            shade: 0.8,
                            maxHeight: 500,
                            id: 'LAY_layuipro', //设定一个id，防止重复弹出
                            btn: ['确认'],
                            moveType: 1, //拖拽模式，0或者1
                            content: otherlist(other_data["other_data_send"]),
                            success: function (layero) {
                                var btn = layero.find('.layui-layer-btn');
                                var btntrue = layero.find('.layui-layer-btn0');
                                btn.css('text-align', 'center');
                            }
                        })
                    }
                })
            },
            reloads: function(){
                var demoReload = $('#demoReload');
                console.log(demoReload.val());
                 $.ajax({
                    url: "/user-sum-select/",
                    dataType: 'json',
                    type: 'POST',
                    data: {"companyname": demoReload.val()},
                    success: function (new_data) {
                        console.log(new_data["usersum_data_send"]);
                        usersum.reload({
                            data: new_data["usersum_data_send"]
                        })
                    }
                })
            },
            createexcel: function () {
                $.ajax({
                    url: "/other-user-data/",
                    dataType: 'json',
                    async: false,
                    type: 'POST'
                });
                $.ajax({
                    url: '/user-sum-send/'
                    ,dataType: 'json'
                    ,type: 'POST'
                    ,async: false
                    ,data: {'date':newdate}
                });
                var excelname1 = "/static/" + new Date().format("yyyyMMdd") + '_user.xlsx';
                var excelname2 = new Date().format("yyyyMMdd") + '_user.xlsx';
                console.log(excelname2);
                var $obj = $("#excelname");
                $obj.attr("href", excelname1);
                $.ajax({
                    url: "/user-sum-create/",
                    dataType: 'json',
                    async: false,
                    type: 'POST',
                    success: function (new_data) {
                        $obj.attr("download", excelname2);
                        layer.msg('下载数据');
                        createstattus=0;
                    }
                });
            },
            dataagg : function () {
                $.ajax({
                    url: "/user-data-agg/",
                    dataType: 'json',
                    type: 'POST',
                    success: function (agg_data) {
                        console.log(agg_data);
                        layer.open({
                            type: 1,
                            title: false, //不显示标题栏
                            closeBtn: false,
                            area: '300px;',
                            shade: 0.8,
                            maxHeight: 500,
                            id: 'LAY_layuipro', //设定一个id，防止重复弹出
                            btn: ['确认'],
                            moveType: 1, //拖拽模式，0或者1
                            content: otherlist(agg_data["agg_data"]),
                            success: function (layero) {
                                var btn = layero.find('.layui-layer-btn');
                                var btntrue = layero.find('.layui-layer-btn0');
                                btn.css('text-align', 'center');
                            }
                        })
                    }
                })
            }
        };

    }
        // $("#excelname").attr("href", "{% static 'test.xlsx' %}");


    function usersumtool(toolid, tableid, sortid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);
            console.log(data);
            if (layEvent === 'details') {
                layer.msg('暂无');
            }
        });
        table.on('sort(usersums)', function(obj){
            console.log(obj.field); //当前排序的字段名
            console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
            var field = obj.field;
            var newdata = usersum.config.data;
            if (obj.type === "desc"){
                function sortprice(a,b){
                   return b[field] - a[field]
                }
                newdata.sort(sortprice);
            } else if (obj.type === "asc") {
                function sortprice(a,b){
                   return  a[field] - b[field]
                }
                newdata.sort(sortprice);
            }
            usersum.reload({
                data: newdata
            });
        });




    }

    function otherlist(otherdata) {
        var contxt = '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300; text-align:center">';
        for (var i = 0; i <= otherdata.length; i++) {
            if (i === otherdata.length) {
                contxt = contxt + '</div>'
            } else {
                $.each(otherdata[i],function (k,v) {
                    contxt = contxt + k + ' : ' + v + '<br>' + '<hr class="layui-bg-red">'
                });
            }
        }
        console.log(contxt);
        return contxt
    }
    var all_content;
    var no_jane_json;
    // var btn = layero.find('.layui-layer-btn');
    // var btntrue = layero.find('.layui-layer-btn0');
    $("#associated").on('click', function () {
        all_content ='<form id="formtree1" name="formtree1" class="layui-form layui-form-pane"><div class="layui-form-item"><label class="layui-form-label" style="color:#000;">公司选择</label><div class="layui-input-block"><select id="rulelist" name="rulelist" lay-filter="rulelist"><option value=""></option>';
        var end_context='</select></div></div><div class="layui-form-item"><label class="layui-form-label" style="color:#000;">简称配置</label><div class="layui-input-block"><input id="rulename" type="text" name="perkey" autocomplete="rulename" placeholder="输入简称" required lay-verify="required" class="layui-input"></div></div></form>';
        $.ajax({
            url: '/company-name-sel/',
            dataType: 'json',
            type: 'POST',
            async: false,
            success: function (no_jane_data) {
                no_jane_json = no_jane_data["no_jane_list"];
                $.each(no_jane_json, function (k,v) {
                    all_content = all_content + '<option value="' + k + '" selected="">' + v + '</option>'
                })
            }
        });
        all_content = all_content + end_context;
        layer.msg(
            content=all_content,
            {
            time: 200000,
            area: ['600px', '260px'],
            //200s后自动关闭
            btn: ['确定', '取消'],
            success: function (layero) {
                var btn = layero.find('.layui-layer-btn');
                var btntrue = layero.find('.layui-layer-btn0');
                form.render('select');
                btn.css('text-align', 'center');
                btntrue.on('click', function () {
                    $.ajax({
                        url: '/company-name-add/',
                        dataType: 'json',
                        type: 'POST',
                        data: {'fullname':no_jane_json[parseInt($("#rulelist").val())], 'janename':$("#rulename").val()},
                        success: function (add_status) {
                            console.log(add_status['status']);
                            if (add_status['status'] == 0){
                                $.ajax({
                                    url: '/user-sum-send/'
                                    ,dataType: 'json'
                                    ,type: 'POST'
                                    ,data: {'date':datetime}
                                    ,success: function (uss_data) {
                                        usersum.reload({
                                            data:uss_data["usersum_data_send"]
                                        })
                                    }
                                })
                            }
                        }
                    })
                })
            }
        });
    });






    $('.demoTable .layui-btn').on('click',
        function() {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        }
    );
});